<!-- 用户管理 -->
<!-- art-full-height 自动计算出页面剩余高度 -->
<!-- art-table-card 一个符合系统样式的 class，同时自动撑满剩余高度 -->
<!-- 更多 useTable 使用示例请移步至 功能示例 下面的 高级表格示例 -->
<template>
  <div class="art-full-height">
    <!-- 搜索栏 -->
    <CustomSearchBar
      v-model="searchForm"
      :form-items="searchFormList"
      @search="handleSearch"
      @reset="resetSearchParams"
    ></CustomSearchBar>

    <ElCard class="art-table-card" shadow="never">
      <!-- 表格头部 -->
      <ArtTableHeader v-model:columns="columnChecks" :loading="loading" @refresh="refreshData">
        <template #left>
          <ElSpace wrap>
            <ElButton @click="showDialog" v-ripple>新增题目</ElButton>
            <!-- <ElButton v-ripple>批量导入</ElButton> -->
            <ElUpload
              :show-file-list="false"
              :accept="'.xlsx'"
              :action="staticUrl.importSubject"
              :headers="uploadHeaders"
              :on-success="uploadSuccess"
            >
              <ElButton v-ripple>批量导入</ElButton>
            </ElUpload>
          </ElSpace>
        </template>
      </ArtTableHeader>

      <!-- 表格 -->
      <ArtTable
        :loading="loading"
        :data="data"
        :columns="columns"
        :pagination="pagination"
        @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange"
      >
        <!-- 原文 -->
        <template #sourceText="{ row }">
          <div v-html="row.sourceText"></div>
        </template>
        <!-- 译文 -->
        <template #translationText="{ row }">
          <div v-html="row.translationText"></div>
        </template>
      </ArtTable>
    </ElCard>

    <!-- 表单 -->
    <customForm
      v-model:visible="visiable"
      :title="title"
      :width="800"
      :label-width="80"
      :form-data="formData"
      @submit="getData"
    ></customForm>

    <!-- 扩展绑定 -->
    <BindExt
      v-model:visible="bindVisiable"
      :subject-id="subjectId"
      @update:visible="updateBindExtVisible"
    ></BindExt>

    <!-- 题目详情 -->
    <SubjectInfo v-model:visible="infoVisiable" :subject-id="subjectId"></SubjectInfo>
  </div>
</template>

<script setup lang="ts">
  import ArtButtonMore, { ButtonMoreItem } from '@/components/core/forms/art-button-more/index.vue'
  import { ElMessage, ElTag } from 'element-plus'
  import { useTable } from '@/composables/useTable'
  import { SearchFormItem } from '@/components/core/forms/art-search-bar/index.vue'
  import { lanDirTagType, systemConfigType, tagType } from '@/maps'
  import { isEmpty } from '@/utils'
  import {
    CustomFormColumnsType,
    CustomInterfaceFormBody,
    optionsBody
  } from '@/components/custom/custom-form/it'
  import { apiAddSubject, apiEditSubject, apiGetSubject, apiSearchSubject } from '@/api/subject'
  import { apiGetSystemConfig } from '@/api/auth'
  import { Edit, Connection, View } from '@element-plus/icons-vue'
  import BindExt from './modules/bindExt.vue'
  import SubjectInfo from './modules/subjectInfo.vue'
  import { staticUrl } from '@/utils/http/url'
  import { useUserStore } from '@/store/modules/user'

  //用户登录的信息
  const { accessToken } = useUserStore()

  //上传请求头
  const uploadHeaders: any = ref<any>({
    Authorization: accessToken
  })

  // 搜索表单
  const searchForm = ref({
    lanDir: undefined,
    rate: undefined,
    territoryId: undefined,
    sourceText: undefined,
    addTime: undefined
  })

  //搜索提交数据
  const searchData = ref({
    lanDir: '',
    rate: '',
    territoryId: '',
    sourceText: '',
    startTime: '',
    endTime: ''
  })

  //搜索表单项
  const searchFormList: SearchFormItem[] = [
    {
      label: '语向',
      key: 'lanDir',
      type: 'select',
      props: {
        placeholder: '请选择语向',
        options: [
          {
            label: '中译英',
            value: 'CE'
          },
          {
            label: '英译中',
            value: 'EC'
          }
        ],
        clearable: true
      }
    },
    {
      label: '难度系数',
      key: 'rate',
      type: 'select',
      props: {
        placeholder: '请选择难度系数',
        options: [],
        clearable: true
      }
    },
    {
      label: '领域',
      key: 'territoryId',
      type: 'select',
      props: {
        placeholder: '请选择领域',
        options: [
          {
            label: '公司法',
            value: '1'
          }
        ],
        clearable: true
      }
    },
    {
      label: '原文',
      key: 'sourceText',
      type: 'input',
      placeholder: '请输入原文',
      clearable: true
    },
    {
      label: '创建时间',
      key: 'addTime',
      type: 'datetime',
      props: {
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD',
        rangeSeparator: '至',
        startPlaceholder: '开始日期',
        endPlaceholder: '结束日期'
      }
    }
  ]

  //弹窗展示状态
  const visiable = ref(false)
  //详情弹窗展示状态
  const infoVisiable = ref(false)
  //绑定弹窗显示状态
  const bindVisiable = ref(false)
  //题目id
  const subjectId = ref(0)
  //弹窗标题
  const title = ref('')
  //表单数据
  const formData = ref<CustomInterfaceFormBody>({
    columns: [
      {
        type: CustomFormColumnsType.select,
        title: '语向',
        name: 'lanDir',
        options: [
          {
            text: '中译英',
            value: 'CE'
          },
          {
            text: '英译中',
            value: 'EC'
          }
        ],
        span: 8
      },
      {
        type: CustomFormColumnsType.select,
        title: '难度系数',
        name: 'rate',
        options: [],
        span: 8
      },
      {
        type: CustomFormColumnsType.select,
        title: '领域',
        name: 'territoryId',
        options: [],
        span: 8
      },
      {
        type: CustomFormColumnsType.editor,
        editorOptions: {
          height: '200px',
          toolbarKeys: ['bold', 'italic', 'underline', 'color', 'undo', 'redo', 'fullScreen']
        },
        title: '原文',
        name: 'sourceText',
        rows: 5
      },
      {
        type: CustomFormColumnsType.editor,
        editorOptions: {
          height: '200px',
          toolbarKeys: ['bold', 'italic', 'underline', 'color', 'undo', 'redo', 'fullScreen']
        },
        title: '译文',
        name: 'translationText',
        rows: 5
      },
      {
        type: CustomFormColumnsType.input,
        title: '来源',
        name: 'from'
      }
    ],
    addFun: apiAddSubject,
    getFun: apiGetSubject,
    editFun: apiEditSubject,
    rules: {
      lanDir: [{ required: true, message: '请选择语向', trigger: 'blur' }],
      rate: [{ required: true, message: '请选择难度系数', trigger: 'blur' }],
      territoryId: [{ required: true, message: '请选择难度领域', trigger: 'blur' }],
      sourceText: [{ required: true, message: '请输入原文', trigger: 'blur' }],
      translationText: [{ required: true, message: '请输入译文', trigger: 'blur' }]
    }
  })

  //语向枚举类型
  const getSubjectLanDirConfig = (type: string): any => {
    return lanDirTagType[type]
  }

  const {
    columns,
    columnChecks,
    data,
    loading,
    pagination,
    getData,
    searchParams,
    resetSearchParams,
    handleSizeChange,
    handleCurrentChange,
    refreshData
  } = useTable({
    // 核心配置
    core: {
      apiFn: apiSearchSubject,
      apiParams: {
        current: 1,
        size: 10,
        ...searchForm.value
      },
      columnsFactory: () => [
        { prop: 'id', width: 60, label: 'id', align: 'center' }, // 序号
        {
          prop: 'lanDir',
          label: '语向',
          align: 'center',
          width: 100,
          formatter: (row: any) => {
            const config = getSubjectLanDirConfig(row.lanDir)
            return h(ElTag, { type: config.type }, () => config.text)
          }
        },
        {
          prop: 'rate',
          label: '难度系数',
          align: 'center',
          width: 100,
          formatter: (row: any) => {
            return h(ElTag, { type: tagType[row.rate] }, () => row.rateName)
          }
        },
        {
          prop: 'territoryName',
          label: '领域',
          width: 120,
          align: 'center'
        },
        {
          prop: 'sourceText',
          label: '原文',
          width: 300,
          align: 'center',
          useSlot: true
        },
        {
          prop: 'translationText',
          label: '译文',
          width: 300,
          align: 'center',
          useSlot: true
        },
        {
          prop: 'from',
          label: '来源',
          align: 'center',
          width: 180
        },
        {
          prop: 'addTime',
          label: '创建日期',
          align: 'center',
          width: 180
        },
        {
          prop: 'operation',
          label: '操作',
          width: 80,
          fixed: 'right', // 固定列
          align: 'center',
          formatter: (row: any) =>
            h('div', [
              h(ArtButtonMore, {
                list: [
                  {
                    key: 'info',
                    label: '详情',
                    icon: View
                  },
                  {
                    key: 'edit',
                    label: '编辑',
                    icon: Edit
                  },
                  {
                    key: 'bind',
                    label: '绑定扩展',
                    icon: Connection
                  }
                ],
                onClick: (item: ButtonMoreItem) => buttonMoreClick(item, row)
              })
            ])
        }
      ]
    }
  })

  //搜索
  const handleSearch = (params: any) => {
    searchData.value.lanDir = params.lanDir
    searchData.value.rate = params.rate
    searchData.value.sourceText = params.sourceText
    searchData.value.territoryId = params.territoryId
    searchData.value.startTime = ''
    searchData.value.endTime = ''
    if (!isEmpty(params.addTime)) {
      searchData.value.startTime = params.addTime[0] + ' 00:00:00'
      searchData.value.endTime = params.addTime[1] + ' 23:59:59'
    }
    // 搜索参数赋值
    Object.assign(searchParams, searchData.value)
    getData()
  }

  //显示弹窗
  const showDialog = (): void => {
    nextTick(() => {
      title.value = '添加题目'
      formData.value.isEdit = false
      visiable.value = true
    })
  }

  //编辑
  const editRecord = (row: any) => {
    title.value = '编辑题目'
    formData.value.isEdit = true
    formData.value.record = row
    visiable.value = true
  }

  //更多按钮点击
  const buttonMoreClick = (item: ButtonMoreItem, row: any) => {
    switch (item.key) {
      case 'edit':
        //编辑
        editRecord(row)
        break
      case 'bind':
        //绑定扩展
        subjectId.value = row.id
        bindVisiable.value = true
        break
      case 'info':
        subjectId.value = row.id
        infoVisiable.value = true
        break
    }
  }

  //绑定扩展
  const updateBindExtVisible = (value: boolean) => {
    if (!value) {
      subjectId.value = 0
    }
  }

  //上传成功
  const uploadSuccess = (response: any) => {
    // console.log(response)
    if (response.code == 200) {
      ElMessage.success('导入成功')
      getData()
    } else {
      ElMessage.error('导入失败')
    }
  }

  //设置表单数据
  const setFormColumns = () => {
    //领域
    apiGetSystemConfig(systemConfigType.territory).then((res: any) => {
      let datas = Object.values(res)
      let options: optionsBody[] = datas.map((item: any) => {
        return {
          text: item.name,
          value: item.id
        }
      })
      let searchOptions = datas.map((item: any) => {
        return {
          label: item.name,
          value: item.id
        }
      })
      formData.value.columns?.forEach((item) => {
        if (item.name == 'territoryId') {
          item.options = options
        }
      })
      searchFormList.forEach((item: any) => {
        if (item.key == 'territoryId') {
          item.props.options = searchOptions
        }
      })
    })
    //难度系数
    apiGetSystemConfig(systemConfigType.subjectRate).then((res: any) => {
      const subjectRateList = Object.values(res)
      const subjectRateOptins = subjectRateList.map((item: any) => {
        return {
          label: item.name,
          value: item.id
        }
      })
      searchFormList.forEach((item: any) => {
        if (item.key == 'rate') {
          item.props.options = subjectRateOptins
        }
      })

      formData.value.columns?.forEach((item) => {
        if (item.name == 'rate') {
          item.options = subjectRateList.map((itemRate: any) => {
            return {
              text: itemRate.name,
              value: itemRate.id
            }
          })
        }
      })
    })
  }

  //加载完成
  onMounted(() => {
    setFormColumns()
  })
</script>
